package com.wz.dhs.controller.system;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wz.dhs.exception.BusinessException;
import com.wz.dhs.mapper.user.SysUserMapper;
import com.wz.dhs.model.PageHandler;
import com.wz.dhs.model.UserContextHolder;
import com.wz.dhs.model.common.PageInfo;
import com.wz.dhs.model.common.Result;
import com.wz.dhs.po.user.SysRole;
import com.wz.dhs.po.user.SysUserEntity;
import com.wz.dhs.po.user.SysUserRole;
import com.wz.dhs.service.base.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleController {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysUserMapper userMapper;


    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public Result<PageInfo<SysRole>> list(SysRole role) {
        PageInfo<SysRole> list = roleService.pageRoleList(role);
        return Result.data(list);
    }


    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public Result<SysRole> getInfo(@PathVariable Long roleId) {
        return Result.data(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @PostMapping
    public Result<String> add(@Validated @RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            throw new BusinessException("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            throw new BusinessException("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(UserContextHolder.getUsername());
        roleService.insertRole(role);
        return Result.success("新增成功");

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping
    public Result<String> edit(@Validated @RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            throw new BusinessException("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            throw new BusinessException("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(UserContextHolder.getUsername());

        if (roleService.updateRole(role) > 0) {
            return Result.data("修改成功");
        }
        throw new BusinessException("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }


    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping("/changeStatus")
    public Result<String> changeStatus(@RequestBody SysRole role) {
        role.setUpdateBy(UserContextHolder.getUsername());
        roleService.updateRoleStatus(role);
        return Result.data("修改成功");
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @DeleteMapping("/{roleIds}")
    public Result<String> remove(@PathVariable Long[] roleIds) {
        roleService.deleteRoleByIds(roleIds);
        return Result.data("删除成功");
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public Result<List<SysRole>> optionselect() {
        return Result.data(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/allocatedList")
    public Result<PageInfo<SysUserEntity>> allocatedList(SysUserEntity user) {
        Page<SysUserEntity> list = userMapper.selectAllocatedList(new Page(user.getPageNum(),user.getPageSize()),user);
        return Result.data(PageHandler.returnPage(list.getRecords(),user,list.getTotal()));
    }

    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/unallocatedList")
    public Result<PageInfo<SysUserEntity>> unallocatedList(SysUserEntity user) {
        Page<SysUserEntity> list = userMapper.selectUnallocatedList(new Page(user.getPageNum(),user.getPageSize()),user);
        return Result.data(PageHandler.returnPage(list.getRecords(),user,list.getTotal()));
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping("/authUser/cancel")
    public Result cancelAuthUser(@RequestBody SysUserRole userRole) {
        roleService.deleteAuthUser(userRole);
        return Result.data("修改成功");
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping("/authUser/cancelAll")
    public Result cancelAuthUserAll(Long roleId, Long[] userIds) {
        roleService.deleteAuthUsers(roleId, userIds);
        return Result.data("修改成功");
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping("/authUser/selectAll")
    public Result selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.insertAuthUsers(roleId, userIds);
        return Result.data("修改成功");
    }


}
